import argparse
import os

from split_audio import split_audio


def create_fcpxml(audio_files, output_file, gap_seconds=20):
    """生成FCPXML文件"""
    # XML头部
    xml_header = """<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE fcpxml>
<fcpxml version="1.11">
    <resources>
        <format frameDuration="1/25s" name="FFVideoFormat1080p25"
            width="1920" id="r0" height="1080"/>"""

    # 生成资源列表
    resources = []
    clips = []
    start_frame = 90000  # 1小时 = 3600秒 * 25帧 = 90000帧
    current_offset = f"{start_frame}/25s"  # 开始时间
    gap_frames = int(gap_seconds * 25)  # 转换间隔时间为帧数

    total_frames = 0
    for i, audio_file in enumerate(audio_files, 1):
        # 使用ffmpeg获取音频时长
        import subprocess

        cmd = ["ffmpeg", "-i", audio_file]
        output = subprocess.run(cmd, capture_output=True).stderr.decode()
        duration_line = [line for line in output.split("\n") if "Duration" in line][0]
        duration_str = duration_line.split("Duration: ")[1].split(",")[0]
        h, m, s = map(float, duration_str.split(":"))
        duration_seconds = h * 3600 + m * 60 + s
        duration_frames = int(duration_seconds * 25)  # 假设25帧每秒
        total_frames += duration_frames + gap_frames

        # 生成资源XML
        resource = f"""
        <asset hasAudio="1" audioChannels="2" duration="{duration_frames}/25s"
         name="{os.path.basename(audio_file)}" id="r{i}" audioSources="1" start="0/1s">
            <media-rep src="file://{os.path.abspath(audio_file)}" kind="original-media"/>
        </asset>"""
        resources.append(resource)

        # 生成片段XML
        clip = f"""
                            <asset-clip ref="r{i}" lane="3" duration="{duration_frames}/25s"
                              name="{os.path.basename(audio_file)}" offset="{current_offset}"
                                start="0/1s" enabled="1"/>"""
        clips.append(clip)

        # 更新偏移量，添加间隔时间
        current_offset = (
            f"{int(current_offset.split('/')[0]) + duration_frames + gap_frames}/25s"
        )

    # 计算总时长（加上开始的3600帧）
    total_duration = f"{total_frames}/25s"

    # XML尾部，使用计算出的总时长，并修改tcStart
    xml_footer = f"""
    </resources>
    <library>
        <event name="Timeline {os.path.basename(output_file)}">
            <project name="Timeline {os.path.basename(output_file)}">
                <sequence tcStart="{start_frame}/25s" tcFormat="NDF" duration="{total_duration}"
                  format="r0">
                    <spine>
                        <gap duration="{total_duration}" name="Gap" offset="{start_frame}/25s"
                          start="{start_frame}/25s">
{''.join(clips)}
                        </gap>
                    </spine>
                </sequence>
            </project>
        </event>
    </library>
</fcpxml>"""

    # 合并输入文件
    with open(output_file, "w", encoding="utf-8") as f:
        f.write(xml_header + "".join(resources) + xml_footer)


def main():
    parser = argparse.ArgumentParser(description="分割音频并创建FCPXML时间线")
    parser.add_argument("input_file", type=str, help="输入音频文件的路径")
    parser.add_argument("--output_dir", type=str, default=None, help="输出目录的路径")
    parser.add_argument(
        "--silence_thresh", type=int, default=-40, help="静默阈值，以dB为单位"
    )
    parser.add_argument(
        "--min_silence_len", type=int, default=10, help="最小静默长度，以秒为单位"
    )
    parser.add_argument(
        "--keep_silence", type=float, default=0.5, help="保留的静默长度，以秒为单位"
    )
    parser.add_argument(
        "--gap",
        type=float,
        default=20.0,
        help="音频片段之间的间隔时间，以秒为单位，默认20秒",
    )

    args = parser.parse_args()
    output_dir = args.output_dir or os.path.dirname(args.input_file)

    # 分割音频
    print("开始分割音频...")
    audio_files = split_audio(
        args.input_file,
        output_dir,
        args.silence_thresh,
        args.min_silence_len,
        args.keep_silence,
    )

    if not audio_files:
        print("音频分割失败")
        return

    # 生成FCPXML
    print("生成FCPXML文件...")
    fcpxml_path = os.path.splitext(args.input_file)[0] + ".fcpxml"
    create_fcpxml(audio_files, fcpxml_path, args.gap)
    print(f"FCPXML文件已生成: {fcpxml_path}")


if __name__ == "__main__":
    main()
